home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1999 March / EnigmA AMIGA RUN 35 (1999)(G.R. Edizioni)(IT)[!][issue 1999-03].iso / earcd / -archivi / -recent2 / gaplib.lha / GAPLib_Beta / genomes / BitMatrix.c next >
C/C++ Source or Header  |  1999-03-05  |  2KB  |  96 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <GAP.h>
  5.  
  6. /*
  7.  * Example bit-matrix genome and functions for Crossover, Mutation,
  8.  * Comparing, Initizlization and Displaying.
  9.  *
  10.  */
  11.  
  12. #define    WIDTH        64
  13. #define    HEIGHT    64
  14.  
  15. struct BMPolyphant {
  16.     unsigned char    matrix[HEIGHT][WIDTH>>3];    /* Rows x Columns, 1 Byte = 8 Bits */
  17.     int    x,y,xb;
  18. };
  19.  
  20. void BMCross(struct BMPolyphant *,struct BMPolyphant *);
  21. void BMInit(struct BMPolyphant *);
  22. void BMMutate(struct BMPolyphant *);
  23. void BMDisplay(struct BMPolyphant *);
  24. double BMDist(struct Polyphant *,struct Polyphant *);
  25.  
  26. void BMInit(struct BMPolyphant *Polly)
  27. {
  28. int    x,y;
  29.  
  30. Polly->x = WIDTH;    /* Width in bits. */
  31. Polly->y = HEIGHT;    /* Height in bits. */
  32. Polly->xb = WIDTH>>3;    /* Width in bytes. */
  33.  
  34. for(x=0;x!=(WIDTH>>3);x++) {
  35.     for(y=0;y!=HEIGHT;y++) {
  36.         Polly->matrix[y][x] = Rnd(256);
  37.     }
  38. }
  39.  
  40. }
  41.  
  42. void BMMutate(struct BMPolyphant *Polly)
  43. {
  44. int fx,fy;
  45.  
  46. if(Rnd(1024)<(Polly->x*Polly->y)) {
  47.     fx = Rnd(Polly->x);
  48.     fy = Rnd(Polly->y);
  49.     Flip(&Polly->matrix[fy][fx>>3],fx&7);
  50. }
  51.  
  52. }
  53.  
  54. void BMCross(struct BMPolyphant *Polly,struct BMPolyphant *Tweety)
  55. {
  56. int    x,y,i,size=Polly->xb;
  57. char    *tmp;
  58.  
  59. if((tmp=malloc(size))!=NULL) {
  60.  
  61.     x = Rnd(Polly->x);
  62.     y = Rnd(Polly->y);
  63.  
  64.     for(i=0;i<y;i++) {    /* Swap rows. */
  65.         memcpy(tmp,Polly->matrix[i],size);
  66.         memcpy(Polly->matrix[i],Tweety->matrix[i],size);
  67.         memcpy(Tweety->matrix[i],tmp,size);
  68.     }
  69.  
  70.     free(tmp);
  71.  
  72.     for(i=0;i<Polly->y;i++) {    /* Swap columns. */
  73.         Crossover(Polly->matrix[i],Tweety->matrix[i],x,size);
  74.     }
  75. }
  76.  
  77. }
  78.  
  79. void BMDisplay(struct BMPolyphant *Polly)
  80. {
  81. int x,y;
  82.  
  83. for(y=0;y<Polly->y;y++) {
  84.     for(x=0;x<Polly->x;x++) {
  85.         fputc((TestBit(Polly->matrix[y],x))?'*':' ',stdout);
  86.     }
  87.     fputc('\n',stdout);
  88. }
  89.  
  90. }
  91.  
  92. double BMDist(struct BMPolyphant *Polly,struct BMPolyphant *Tweety)
  93. {
  94. return(HammingDist(Polly.matrix,Tweety.matrix,(WIDTH>>3)*HEIGHT));
  95. }
  96.